package com.quanyan.orderpay.service.impl;

import com.alibaba.rocketmq.common.message.MessageExt;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.enums.MqConsumerStatus;
import com.quanyan.order.entity.OrderMq;
import com.quanyan.order.entity.OrderMqExample;
import com.quanyan.order.mapper.OrderMqMapper;
import com.quanyan.orderpay.component.QcMsgClientImpl;
import com.quanyan.orderpay.request.WithdrawPayInfo;
import com.quanyan.orderpay.response.mq.OrderCallBackMsg;
import com.quanyan.orderpay.response.mq.OrderNotifyMsg;
import com.quanyan.orderpay.service.MqConsumerService;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.orderpay.service.OrderProcessService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by wmb on 2016/8/8.
 */
@Service("mqConsumerService")
public class MqConsumerServiceImpl implements MqConsumerService {
    @Autowired
    private OrderMqMapper orderMqMapper;
    @Autowired
    private OrderProcessService orderProcessService;
    private Logger logger = LoggerFactory.getLogger(QcMsgClientImpl.class);
    @Override
    public MqConsumerStatus orderCallBack(MessageExt messageExt) {
        Gson gson = new GsonBuilder().create();
        byte[] bodyByte = messageExt.getBody();
        //获取成功返回的信息
        OrderCallBackMsg orderCallBackMsg= (OrderCallBackMsg) ObjectUtil.toObject(bodyByte);
        logger.warn("回调结果:"+gson.toJson(orderCallBackMsg));
        if(null!=orderCallBackMsg.getState()&&orderCallBackMsg.getState().equals(OrderCallBackMsg.SUCCESS)){
            if(null!=orderCallBackMsg.getOrderNo()&&null!=orderCallBackMsg.getType()){
                OrderMqExample orderMqExample=new OrderMqExample();
                orderMqExample.createCriteria().andTypeEqualTo(orderCallBackMsg.getType())
                        .andOrdernoEqualTo(orderCallBackMsg.getOrderNo());
                orderMqMapper.deleteByExample(orderMqExample);
            }
        }
        return MqConsumerStatus.CONSUMER_SUCCESS;
    }

    @Override
    public MqConsumerStatus weChatWithdraw(MessageExt messageExt) {
        Gson gson = new GsonBuilder().create();
        byte[] bodyByte = messageExt.getBody();
        WithdrawPayInfo payInfo = (WithdrawPayInfo) ObjectUtil.toObject(bodyByte);
        logger.info("微信提现："+gson.toJson(payInfo));
        try{
            orderProcessService.transferFundByWechat(payInfo);
        }catch (Exception e){
            logger.info("微信提现失败："+e.getMessage());
            return MqConsumerStatus.CONSUMER_SUCCESS;
        }
        return MqConsumerStatus.CONSUMER_SUCCESS;
    }
}
